package com.yjc.hire.config;

import io.netty.util.internal.StringUtil;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransaction;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * </p>
 *
 * @author jcyin
 * @since 2025/7/20
 * </p>
 */
@Slf4j
@Component
@Aspect
public class SeataTransactionAspect {
    @Before("execution(* com.yjc.hire.*.service.impl..*.*(..))")
    public void beforeTransaction(JoinPoint joinPoint) throws TransactionException {
        //手动开启事务
        GlobalTransaction gt = GlobalTransactionContext.getCurrentOrCreate();
        gt.begin();
    }

    /**
     * 捕获到异常进行回滚
     * @param throwable
     * @throws TransactionException
     */
    @AfterThrowing(
            throwing = "throwable",
            pointcut = "execution(* com.yjc.hire.*.service.impl..*.*(..))"
    )
    public void seataRollback(Throwable throwable) throws TransactionException {
        log.info("seataRollback exception", throwable);
        String xid = RootContext.getXID();
        if (StringUtils.isNoneBlank(xid)) {
            GlobalTransactionContext.reload(xid).rollback();
        }
    }
}
